<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">公{{ page.total }}</span>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="list">
          <!-- 在表格中 要显示属性需要给 type=index -->
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" align="center">
            <!-- 插槽 -->
            <template v-slot=" { row }">
              <img @click="showQrCode(row.staffPhoto)" v-imagerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber"  label="工号" sortable="" />
          <el-table-column :formatter="formatEmployment" prop="formOfEmployment" label="聘用形式" sortable="" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <!-- 使用昨夜雨插槽来做  过滤器 -->
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
           <template v-slot=" { row } ">
            {{ row.timeOfEntry | formatDate }}
           </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" >
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope=" {row } ">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination layout="prev, pager, next" 
          :page-size="page.size"
          :current-page="page.page"
          :total="page.total"
          @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置组件弹层 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 二维码 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 放置分配组件 -->
    <assign-role ref="assignRole" :showRoleDialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employess'
import EmployeeEnum from '@/api/constant/employees' 
import AddEmployee from './components/add-employee'
import { formatDate } from '@/filters'
import AssignRole from './components/assign.role'
import QrCode from 'qrcode'

export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [], // 接收数组
      page: {
        page: 1, // 页码
        size: 10,   // 每页条数
        total: 0 // 总数
      },
      loading: false, // 显示遮罩层
      showDialog: false, // 默认关系弹层
      showCodeDialog: false, // 显示二维码弹层
      showRoleDialog: false, // 分配角色的弹层
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
   async getEmployeeList() {
    this.loading = true
     const { total, rows } = await getEmployeeList(this.page)
     this.page.total = total
     this.list = rows
     this.loading = false
    },
    changePage(newPage) {
      this.page.page =  newPage // 赋值最新页码
      this.getEmployeeList() // 重新拉取数据
    },
   // 格式化聘用形式
   formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportData () {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 导出excel
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取员工的接口 页码 每一页的条数
       const { rows } = await getEmployeeList({ page: 1, size: this.page.total})
      // 返回的 data 就是 要导出的结构
      const data = this.formatJson(headers, rows)
      // 定义复杂表头 导出
      // 一个数组 代表一行
      // const multiHeader = [['a', 'b', 'c', 'b', 'e', 'f', 'g'],['1','2','3']]
      const multiHeader = [['姓名','主要信息','','','','','部门']]
      const merges = ['A1:A2','B1:F1','G1:G2']
       excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          multiHeader, // 复杂表头
          merges, // 合并选项
      })
        // excel 是引入文件的导出对象
        // excel.export_json_to_excel({
        //   header: ['姓名','工资'],
        //   data: [['张三',3000], ['李四', 5000]],  // 一条数据 一个数组
        //   filename: '员工工资表'
        // })
        // 要转化数据结构 还有和表头的顺序对应上
        // 要求转出的是中文  
      }) 
    },
    // 将表头数据和数据进行对应
    // 将 数组对象 [{}]  转换成  数组数组 [[]]
    formatJson(headers, rows) {
      return rows.map( item => {
        // item是一个对象
       return Object.keys(headers).map(key => {
        // 需要判断 字段
        if(headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
          // 格式化日期
          return  formatDate(item[headers[key]])
        } else if(headers[key] === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
          return obj ? item.value : '未知'
        }
         return item[headers[key]]
        })
      })
      // 最简单的写法
      // return row.map(item => Object.keys(headers).map(key => item[headers[kes]]))
    },
    showQrCode(url) {
      // 当 url存在的时候 才弹出
      if(url) {
        this.showCodeDialog = true
        // 将地址转化成二维码
        // 等数据更新完毕之后 
        this.$nextTick( ()=> {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户还未上传对象')
      }
    },
    async editRole(id) {
      // 显示弹出层
      this.userId = id  // props 赋值
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>
</style>